package com.hiruss.efair.persistence;

import com.hiruss.efair.entities.Advertisement;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.persistence.*;
//import org.apache.commons.io.FileUtils;

/**
 * This class manages Contacts
 * @author icbt
 */
public class AdvertisementManager {

		private static AdvertisementManager instance = new AdvertisementManager();

		public static AdvertisementManager getInstance() {
				return instance;
		}
		private EntityManagerFactory emf =
				Persistence.createEntityManagerFactory("eFairPU");

		/**
		 * This method saves a contact in the database
		 * @param contact Contacts to be added
		 * @return true is the operations succeeds, false otherwise
		 */
		public boolean addAdvertisement(Advertisement add) {
				// copying the contact image to C:\\Java
				// apache commonslibrary automatically comes with struts
				try {
//            FileUtils.copyFile(contact.getContactimage(), new File("G:\\Java\\John.jpg"));
				} catch (Exception ex) {
						ex.printStackTrace();
				}

				EntityManager em = emf.createEntityManager();
				em.getTransaction().begin();
				em.persist(add);
				em.getTransaction().commit();
				return true;
		}

		public List<Advertisement> getAllAdvertisements() {

				EntityManager em = emf.createEntityManager();
				em.getTransaction().begin();
				Query q = em.createQuery("SELECT ad FROM Advertisement ad");  //"Contacts is the name of the entity"
				List results = q.getResultList();
				em.getTransaction().commit();
				return results;
		}

		public List<Advertisement> getAdvertisementsByCategory(String category) {

				EntityManager em = emf.createEntityManager();
				em.getTransaction().begin();
				Query q = em.createQuery("SELECT ad FROM Advertisement ad where ad.category = '" + category + "'");
				List results = q.getResultList();
				em.getTransaction().commit();
				return results;
		}

		public List<Advertisement> getAdvertisementsByItem(String item) {

				EntityManager em = emf.createEntityManager();
				em.getTransaction().begin();
				Query q = em.createQuery("SELECT ad FROM Advertisement ad where ad.item like '%" + item + "%'");
				List results = q.getResultList();
				em.getTransaction().commit();
				return results;
		}

		private AdvertisementManager() {
		}
}
